var express = require('express');
var router = express.Router();
const { packRes } = require('../utils/packRes')
const multiparty = require('multiparty')
var {customQuery} = require('../mysql/index')
const path = require('path')
const fs = require('fs')
const fullPath = './public/images/banner/'

//获取数据
router.get('/', function (req, res, next) {
    const sql = 'SELECT * FROM banner';
    customQuery(sql).then(results=>{
        res.status(200).send({
            code:200,
            list:results,
            msg:'获取成功'
        });
    })
});


//添加图片
router.post('/add', function (req, res, next) {
    console.log('进入图片上传接口')
    const from = new multiparty.Form();
    console.log('from',from)
    from.uploadDir = fullPath;
    from.parse(req, (err, files, file) => {
        console.log(222,err, files, file)
        if (err || !file.file[0]) {
            res.status(200).send(packRes(400, '', '图片上传失败'));
            return;
        }
        let { name: [name], target: [target] } = files;
        console.log('file.file[0].path',file.file[0].path)
        
        
        let url = '';
        if (process.env.NODE_ENV === 'development') {
            url = `${req.protocol}://${req.headers.host}${file.file[0].path.replace('public', '')}`;
        } else {
            url = 'http://www.hnclove.com'+file.file[0].path.replace('public', '');
        }
        // let url = file.file[0].path;
        url = url.replace(/[\/\\]/g, '\\\\'); // Replace '/' with '\\'
        const sql = `INSERT INTO banner (name, target, url) VALUES ('${name}', '${target}', '${url}')`;
        // Execute the query
        customQuery(sql).then(results => {
            return res.status(200).send({ code: 200, msg: '上传成功', list: results });
        })
    });
});
router.post('/delete/:id', function (req, res, next) {
    const id = req.params.id;
    const sql = `SELECT url FROM banner WHERE id=${id}`;
    customQuery(sql).then(results => {
        if (results.length > 0) {
            const url = results[0].url.split(/banner./)[1]
            fs.unlink(path.join(__dirname, '../public/images/banner', url), (err) => {
                if (err) {
                    console.error(err);
                    return;
                }
            });
            const deleteSql = `DELETE FROM banner WHERE id=${id}`;
            customQuery(deleteSql).then(results => {
                res.status(200).send({ code: 200, msg: '删除成功', list: results });
            })
        } else {
            res.status(200).send({ code: 400, msg: '删除失败，未找到对应数据' });
        }
    });
});



module.exports = router;
